/**
 * Created by sofwu on 2016/12/22 0022.
 */
import qs from 'query-string';
import config from '../configs/Service';
import {getAccessToken, getAuthToken, remAuthToken} from './../services/token'
import logger from './logger'

const urlPrefix = config.domain + config.apiPath;
const isDebuggingInChrome = __DEV__ && !!window.navigator.userAgent;

function makeHeader(){
  const accessToken = getAccessToken()
  const authToken = getAuthToken()
  // const authToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJvNE5oVDB1V1JOT3hoZ19Pc1VxQWlidnhEUVFZIiwianRpIjoiZUZBR3E4Vm1udTlMdWRWSyIsIm5iZiI6MTUyMTc5Mjk5MCwiZXhwIjoxNjc3MzEyOTkwLCJpYXQiOjE1MjE3OTI5OTAsImlzcyI6Imh0dHBzOlwvXC90YW8udnl4amouY29tXC9hcGlcL3VzZXJcL2xvZ2luIn0.tu2x3cpFI1r3z8TMpnDyDgt2zqOP8BoCKmcXNtFPjz0"
  // const authToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMzkyNTQ0MDA4NCIsImp0aSI6ImJHU3BaOHo4bXp4RjVRMmkiLCJuYmYiOjE1NTU1NzA1NTIsImV4cCI6MTU4NzEwNjU1MiwiaWF0IjoxNTU1NTcwNTUyLCJpc3MiOiJodHRwczpcL1wvdGFvLnZ5eGpqLmNvbVwvYXBpXC91c2VyXC9waG9uZV9sb2dpbiJ9.K7AA0EH2QR8aaQ1l_8BAlcx-OfZSYWceRVU4ziEUq-c"

  let header = {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  };

  if(accessToken){
    header["Access-token"] = accessToken;
  }
  if(authToken) {
    header['Authorization'] = 'Bearer '+authToken;
  }

  return header;
}

function uploadHeader(){
  const accessToken = getAccessToken()
  const authToken = getAuthToken()

  return {
    'Content-Type': 'multipart/form-data',
    'Access-token': accessToken,
    'Authorization' : 'Bearer ' + authToken,
  }
}

function filterJSON(res) {
  if (isDebuggingInChrome) {
    logger.info(`json: `, res);
  }
  return res;
}

function filterStatus(res) {
  if (isDebuggingInChrome) {
    logger.info(`RSSPONSE: `, res);
  }
  
  if (res.status >= 200 && res.status < 399) {
    return res.json();
  }
  else {
    return res.json().then((json)=>{
      let error = new Error(json.data.message);
      error.message = json.data.message;
      error.errors = true;
      error.status = res.status;
      throw error;
    })
  }
}


export function get(url, params) {
  url = urlPrefix + url;
  if (params) {
    url += `?${qs.stringify(params)}`;
  }

  const header = makeHeader();

  if (isDebuggingInChrome) {
    logger.info('------------get request info-------------');
    logger.info(`GET: `, url);
    logger.info(`Params: `, params)
    logger.info('Header:', header);
    logger.info('-----------//request info//----------');
  }
  


  return fetch(url,{
    method: 'GET',
    headers: header,
  })
  .then(filterStatus)
  .then(filterJSON);
}


export function post(url, body) {
  url = urlPrefix + url;
  const header = makeHeader();
  if (isDebuggingInChrome) {
    logger.info('------------post request info-------------');
    logger.info(`POST: `, url);
    logger.info(`Body: `, body);
    logger.info('Header:', header);
    logger.info('-----------//request info//----------');
  }

  return fetch(url, {
    method: 'POST',
    headers: header,
    body: JSON.stringify(body)
  })
  .then(filterStatus)
  .then(filterJSON);
}


export function put(url, body) {
  url = urlPrefix + url;

  const header = makeHeader();
  if (isDebuggingInChrome) {
    logger.info('------------post request info-------------');
    logger.info(`PUT: `, url);
    logger.info(`Body: `, body);
    logger.info('Header:', header);
    logger.info('-----------//request info//----------');
  }

  return fetch(url, {
    method: 'PUT',
    headers: header,
    body: JSON.stringify(body)
  })
    .then(filterStatus)
    .then(filterJSON);
}


export function upload(url, formData) {
  url = urlPrefix + url;

  const header = uploadHeader();
  if (isDebuggingInChrome) {
    console.info('------------request info-------------');
    console.info(`POST: `, url);
    console.info(`Body: `, formData);
    console.info('Header:', header);
    console.info('-----------//request info//----------');
  }

  return fetch(url, {
    method: 'POST',
    headers: header,
    body: formData
  })
    .then(filterStatus)
    .then(filterJSON);
}


export function del(url, params) {
  url = urlPrefix + url;

  const header = makeHeader();

  if (isDebuggingInChrome) {
    logger.info('------------get request info-------------');
    logger.info(`GET: `, url);
    logger.info(`Params: `, params)
    logger.info('Header:', header);
    logger.info('-----------//request info//----------');
  }



  return fetch(url,{
    method: 'DELETE',
    headers: header,
  })
    .then(filterStatus)
    .then(filterJSON);
}